package com.sky.service.impl;

import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressBookServiceImpl implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    /**
     * 条件查询当前登录用户的所有地址信息
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<AddressBook> list(Long userId) {
        //构建地址簿对象 设置查询条件
        AddressBook addressBook = AddressBook.builder()
                .userId(userId)
                .build();
        List<AddressBook> list = addressBookMapper.list(addressBook);
        return list;
    }

    /**
     * 新增地址
     *
     * @param addressBook
     */
    @Override
    public void save(AddressBook addressBook) {
        //通过ThreadLocal获取用户id
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        //设置地址默认为0
        addressBook.setIsDefault(StatusConstant.DISABLE);
        addressBookMapper.insert(addressBook);
    }

    /**
     * 根据id查询地址信息
     *
     * @param id
     * @return
     */
    @Override
    public AddressBook getById(Long id) {
        AddressBook addressBook = addressBookMapper.getById(id);
        return addressBook;
    }

    /**
     * 根据id修改地址信息
     *
     * @param addressBook
     */
    @Override
    public void update(AddressBook addressBook) {
        addressBookMapper.update(addressBook);
    }

    /**
     * 设置默认地址
     *
     * @param addressBook
     */
    @Transactional
    @Override
    public void setDefault(AddressBook addressBook) {
        //1.先将当前用户的所有地址修改成非默认的 update address_book set is_default = ? where user_id = ?
        //通过ThreadLocal获取用户id
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId); //设置用户id
        addressBook.setIsDefault(StatusConstant.DISABLE); //设置为非默认
        //因为在修改地址信息的时候已经将所有的字段都做成了动态sql所有这里直接调用update方法即可
        //addressBookMapper.update(addressBook);
        //第二种方式
        addressBookMapper.updateIsDefaultByUserId(addressBook);

        //2.将当前地址修改为默认地址 update address_book set is_default = ? where id = ?
        addressBook.setIsDefault(StatusConstant.ENABLE); //设置为默认
        addressBookMapper.update(addressBook);
    }

    /**
     * 根据id删除地址
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        addressBookMapper.deleteById(id);
    }

    /**
     * 根据id查询默认地址
     * @param addressBook
     * @return
     */
    @Override
    public List<AddressBook> getDefault(AddressBook addressBook) {
        return addressBookMapper.list(addressBook);
    }
}
